define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 加载存储配置
            Controller.api.loadConfigs();
            
            // 初始化上传表单
            Controller.api.initUpload();
            
            // 初始化文件列表
            Controller.api.initFileList();
            
            // 初始化统计信息
            Controller.api.loadStatistics();
        },
        
        api: {
            loadConfigs: function() {
                $.ajax({
                    url: 'yuncunchu/config/index',
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        if (data.rows && data.rows.length > 0) {
                            var html = '<option value="">请选择存储配置</option>';
                            data.rows.forEach(function(config) {
                                if (config.status == 1) { // 只显示启用的配置
                                    var isDefault = config.is_default == 1 ? ' (默认)' : '';
                                    html += '<option value="' + config.id + '">' + config.name + ' - ' + config.type_text + isDefault + '</option>';
                                }
                            });
                            $('#config-select').html(html);
                            $('#batch-config-select').html(html);
                        }
                    },
                    error: function() {
                        console.error('加载配置失败');
                    }
                });
            },
            
            initUpload: function() {
                // 单文件上传
                $('#upload-form').on('submit', function(e) {
                    e.preventDefault();
                    
                    var formData = new FormData(this);
                    var configId = $('#config-select').val();
                    if (!configId) {
                        alert('请选择存储配置');
                        return;
                    }
                    formData.append('config_id', configId);
                    formData.append('module', 'example');
                    formData.append('action', 'upload');
                    
                    $.ajax({
                        url: 'yuncunchu/upload/index',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            if (response.code === 1) {
                                $('#upload-result').html('<div class="alert alert-success">上传成功！文件ID：' + response.data.file_id + '</div>');
                                Controller.api.refreshFiles();
                                Controller.api.loadStatistics();
                            } else {
                                $('#upload-result').html('<div class="alert alert-danger">上传失败：' + response.msg + '</div>');
                            }
                        },
                        error: function() {
                            $('#upload-result').html('<div class="alert alert-danger">上传失败：网络错误</div>');
                        }
                    });
                });
                
                // 多文件上传
                $('#batch-upload-form').on('submit', function(e) {
                    e.preventDefault();
                    
                    var formData = new FormData(this);
                    var configId = $('#batch-config-select').val();
                    if (!configId) {
                        alert('请选择存储配置');
                        return;
                    }
                    formData.append('config_id', configId);
                    formData.append('module', 'example');
                    formData.append('action', 'upload');
                    
                    $.ajax({
                        url: 'yuncunchu/upload/batch',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            if (response.code === 1) {
                                var html = '<div class="alert alert-success">批量上传完成！成功：' + response.data.success_count + '，失败：' + response.data.failed_count + '</div>';
                                if (response.data.failed_files.length > 0) {
                                    html += '<div class="alert alert-warning">失败文件：<ul>';
                                    response.data.failed_files.forEach(function(file) {
                                        html += '<li>' + file.message + '</li>';
                                    });
                                    html += '</ul></div>';
                                }
                                $('#batch-upload-result').html(html);
                                Controller.api.refreshFiles();
                                Controller.api.loadStatistics();
                            } else {
                                $('#batch-upload-result').html('<div class="alert alert-danger">批量上传失败：' + response.msg + '</div>');
                            }
                        },
                        error: function() {
                            $('#batch-upload-result').html('<div class="alert alert-danger">批量上传失败：网络错误</div>');
                        }
                    });
                });
            },
            
            initFileList: function() {
                Controller.api.refreshFiles();
            },
            
            refreshFiles: function() {
                $.ajax({
                    url: 'yuncunchu/example/files',
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            var html = '';
                            response.data.rows.forEach(function(file) {
                                html += '<tr>';
                                html += '<td>' + file.id + '</td>';
                                html += '<td>' + file.original_name + '</td>';
                                html += '<td>' + file.file_size_text + '</td>';
                                html += '<td>' + file.file_type + '</td>';
                                html += '<td>' + file.createtime_text + '</td>';
                                html += '<td>';
                                html += '<a href="' + file.file_url + '" target="_blank" class="btn btn-xs btn-info">查看</a> ';
                                html += '<button onclick="Controller.api.deleteFile(' + file.id + ')" class="btn btn-xs btn-danger">删除</button>';
                                html += '</td>';
                                html += '</tr>';
                            });
                            $('#files-table tbody').html(html);
                        }
                    }
                });
            },
            
            deleteFile: function(fileId) {
                if (confirm('确定要删除这个文件吗？')) {
                    $.ajax({
                        url: 'yuncunchu/example/delete',
                        type: 'POST',
                        data: {file_id: fileId},
                        success: function(response) {
                            if (response.code === 1) {
                                alert('删除成功！');
                                Controller.api.refreshFiles();
                                Controller.api.loadStatistics();
                            } else {
                                alert('删除失败：' + response.msg);
                            }
                        }
                    });
                }
            },
            
            loadStatistics: function() {
                $.ajax({
                    url: 'yuncunchu/example/statistics',
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            $('#total-files').text(response.data.total_files);
                            $('#total-size').text(response.data.total_size_text);
                            // 这里可以添加今日上传统计
                            $('#today-uploads').text('0');
                        }
                    }
                });
            }
        }
    };
    
    // 暴露给全局使用
    window.Controller = Controller;
    
    return Controller;
});
